<template>
    <div class="add-event-listeners">
        <div ref="parentRef" class="ael-parent">
            这是父元素
            <div ref="childRef" class="ael-child">这是子元素</div>
        </div>
        <div class="vary-height">{{ width }}</div>
    </div>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
const controller = new AbortController()
const width = ref(0)
const windowResize = function (event) {
    console.log(event)
    width.value = event.currentTarget.innerWidth
    if (width.value < 1000) {
        // this.abort()
        console.log('小于1000', this)
        controller.abort()
    }
}
window.addEventListener('resize', windowResize, {
    capture: false,
    signal: controller.signal,
})
// 父子元素事件监听测试
const parentRef = ref<HTMLDivElement | null>(null)
const childRef = ref<HTMLDivElement | null>(null)
const clickParentFun = () => {
    console.log('父元素点击')
}
const clickChildFun = () => () => {
    console.log('子元素点击')
}
onMounted(() => {
    parentRef.value?.addEventListener('click', clickParentFun, {
        capture: true, // 是否使用捕获阶段
        once: true, // 是否只需触发一次
        passive: true, // 是否可以取消默认事件 event.preventDefault(),
        signal: controller.signal, // 打断控制器信号
    })
    childRef.value?.addEventListener('click', clickChildFun, false)
})
onUnmounted(() => {
    parentRef.value?.removeEventListener('click', clickParentFun)
    childRef.value?.removeEventListener('click', clickChildFun)
})
</script>
<style lang="scss" scoped>
.add-event-listeners {
    .ael-parent {
        background-color: #0ff;
        padding: 10px;
        .ael-child {
            background-color: #f0f;
            padding: 10px;
        }
    }
    .vary-height {
        height: 400vh;
    }
}
</style>
